package com.docjohnson.pamphlet.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.os.AsyncTask;

public class ImageDownloader {
	
	public ImageDownloader(){
		
	}

	public void downloadImage(String urlString, final String folder, final String fileName, final ImageDownloadFinishListener listener) {
		AsyncTask<String, Void, String> imageDownloaderAsyncTask = new AsyncTask<String, Void, String>() {

			@Override
			protected String doInBackground(String... params) {
				if((new File(params[1]+"/"+params[2]).exists())){
					return params[1]+"/"+params[2];
				}
				URL url = null;
					try {
						url = new URL(params[0]);
						URLConnection connection = url.openConnection();
						connection.connect();
						int fileLength = connection.getContentLength();

						InputStream input = new BufferedInputStream(url.openStream());
						OutputStream output = new FileOutputStream(params[1]+"/"+params[2]);

						byte data[] = new byte[1024];
						long total = 0;
						int count;
						while ((count = input.read(data)) != -1) {
							total += count;
							output.write(data, 0, count);
						}

						output.flush();
						output.close();
						input.close();
					} catch (Exception e) {
						e.printStackTrace();
					}

				return params[1]+"/"+params[2];
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if(listener != null)
					listener.onImageDownloaded(result);
			}

		};
		imageDownloaderAsyncTask.execute(urlString, folder, fileName);
	}
}
